#!/usr/bin/python
# -*- coding: UTF-8 -*-
 

import xml.dom.minidom
import resolve_svd_mo as svd_inf

def gen_reg_list(svd_name):
    DOMTree = xml.dom.minidom.parse(svd_name)
    collection = DOMTree.documentElement

    # 在集合中获取所有外设
    peripherals = collection.getElementsByTagName("peripheral")
    reg_str_list = []
    reg_str = "{\n"
    reg_cnt = 0
    reg_info_dict = []

    for peri in  peripherals:
        name = peri.getElementsByTagName('name')[0].childNodes[0].data
        addr = peri.getElementsByTagName('baseAddress')[0].childNodes[0].data

        if peri.getElementsByTagName('register').length != 0:
            # peri.getElementsByTagName("register")[0].childNodes[0].data
            reg_info_dict = svd_inf.get_peri_regs_info(peri.getElementsByTagName('register'))
        else:
            print("inherit: " + peri.getElementsByTagName("name")[0].childNodes[0].data)

        for key in reg_info_dict:
            # addr, name, reset_val, access, rw_msk, wo_msk, ro_msk, 
            item_addr = hex(int(reg_info_dict[key][1][0:7], 16) + int(addr, 16))
            reg_rw_msk = svd_inf.get_reg_msk(reg_info_dict[key][5], 'WR')
            reg_wo_msk = svd_inf.get_reg_msk(reg_info_dict[key][5], 'WO')
            reg_ro_msk = svd_inf.get_reg_msk(reg_info_dict[key][5], 'RO')
            # reg_item = item_addr , reg_info_dict[key][0], reg_info_dict[key][2], reg_access_dict[reg_info_dict[key][4]], reg_rw_msk, reg_wo_msk, reg_ro_msk
            reg_str_item = "     {" + str(item_addr) + ", " + \
                            '''"''' + str(reg_info_dict[key][0]) + '''"''' + ", " + str(reg_info_dict[key][2])+ ", " + \
                            '''"''' + str(svd_inf.reg_access_dict[reg_info_dict[key][4]])  + '''"''' + ", " + \
                            str(reg_rw_msk) + ", " + str(reg_wo_msk) + ", " + str(reg_ro_msk) + "}"

            # reg_list.append(reg_item)
            reg_str = reg_str + reg_str_item + ",\n"
            reg_str_list.append(reg_str_item)
            reg_cnt = reg_cnt + 1

    reg_str = reg_str + "};\n"
#     print('''
# typedef struct {
# 	u32  addr;
# 	char* p_name;
# 	u32  reset_val;
# 	char* p_access;
# 	u32  wr_access;
# 	u32  wo_access;
# 	u32  ro_access;
# } rj_reg_s;
# ''')

    print("\n****************reg list****************")
    print("#define REG_NUM         (" + str(reg_cnt) + ")")
    print("rj_reg_s const g_reg_list[REG_NUM] =")
    print(reg_str)

